<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=0,shrink-to-fit=no, viewport-fit=cover">
    <meta name="keywords" content="蓝桥到家">
    <meta name="description" itemprop="description" content="生鲜副食、饮品乳品、鲜花蛋糕">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>注册</title>
    <link rel="stylesheet" type="text/css" href="../styles/reset.css"/>
    <link rel="stylesheet" type="text/css" href="../styles/login.css">
    <link rel="stylesheet" type="text/css" href="../styles/common.css"/>
    <script src="../js/common.js"></script>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <style>
        .error {
            color: #ff4d4f;
            font-size: 0.1rem;
            margin-top: 0.1rem;
            display: block;
        }
        .code {
            background-color: #1677ff;
        }
        .code.disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }


    </style>
</head>

<body>
<div class="wrap" id="app">
    <div class="container">
        <!-- logo start-->
        <div class="header_logo">
            <img src="https://static.shiyanlou.com/lanqiao/frontend/dist/img/lanqiao-logo.1bbdf85.svg"/>
        </div>
        <!-- logo end -->
        <!-- 注册 start-->
        <div class="login_item">
            <span class="login_text">手机号</span>
            <input class="login_input"
                   type="tel"
                   v-model="form.phone"
                   maxlength="11"
                   @blur="validateField('phone')"
                   placeholder="输入手机号"/>
            <span class="error" v-if="errors.phone">{{errors.phone}}></span>
        </div>
        <div class="login_item">
            <span class="login_text">验证码</span>
            <div class="auth_div">
                <input
                        v-model="form.captcha"
                        class="login_input"
                        type="text" maxlength="4"
                        @blur="validateField('captcha')"
                        placeholder="输入验证码"/>
                <span class="error" v-if="errors.captcha">{{errors.captcha}}</span>
                <div  @click="getCaptcha" :class="{disabled:isCodeDisabled}" class="code">
                    <span v-if="!isCodeDisabled">获取验证码</span>
                    <span v-else>{{countdown}}秒后获取</span>
                </div>
            </div>
        </div>
        <div class="login_item">
            <span class="login_text">密码</span>
            <input class="login_input"
                   type="password"
                   v-model="form.password"
                   @blur="validateField('password')"
                   maxlength="11"
                   placeholder="设置您的登录密码"/>
            <div class="error" v-if="errors.password">{{errors.password}}></div>
        </div>
        <div class="login_button">
            <a @click="handleRegister" :class="{ disabled: isLoading }">
                <span v-if="isLoading">注册中...</span>
                <span v-else>注册</span></a>
        </div>
        <div class="register_div">
            <a href="login.html" class="register_text">
                已有账号，请登录
            </a>
        </div>
        <!-- 注册 end-->

    </div>
</div>
<script>
    const {createApp, ref} = Vue
    createApp({
        setup() {
            const form = ref({
                phone: '',
                captcha: '',
                password: ''
            })
            const errors = ref({
                phone: '',
                captcha: '',
                password: ''
            })

            // 状态管理
            const captchaCountdown = ref(0)

            // 验证字段
            const validateField = (field) => {
                errors.value[field] = ''
                switch (field) {
                    case 'phone':
                        const phoneReg = /^1[3-9]\d{9}$/;
                        if (!form.value.phone) {
                            errors.value.phone = '请输入手机号码';
                        } else if (!phoneReg.test(form.value.phone)) {
                            errors.value.phone = '请输入有效的手机号码';
                        }
                        break;

                    case 'captcha':
                        if (!form.value.captcha) {
                            errors.value.captcha = '请输入验证码';
                        } else if (form.value.captcha.length !== 4) {
                            errors.value.captcha = '验证码错误';
                        }
                        break;

                    case 'password':
                        if (!form.value.password) {
                            errors.value.password = '请输入密码';
                        } else if (form.value.password.length < 6) {
                            errors.value.password = '密码长度不能少于6位';
                        } else if (form.value.password.length > 20) {
                            errors.value.password = '密码长度不能超过20位';
                        }
                        break;
                }

            }
            // 验证整个表单
            const validateForm = () => {
                let isValid = true;

                // 验证所有字段
                ['phone', 'captcha', 'password'].forEach(field => {
                    validateField(field);
                    if (errors.value[field]) {
                        isValid = false;
                    }
                });

                return isValid;
            }

            const isLoading = ref(false)
            // 验证码相关状态
            const isCodeDisabled = ref(false) // 控制按钮是否禁用
            const countdown = ref(60) // 倒计时秒数
            let countdownTimer = null // 倒计时定时器

            //获取验证码
            const getCaptcha = async () => {
                //判断手机号是否有效
                validateField('phone')
                if (errors.value.phone) {
                    return;
                }

                // 模拟发送验证码
                try {

                    // 启动倒计时
                    isCodeDisabled.value = true;
                    countdown.value = 60;

                    // 清除可能存在的旧定时器
                    if (countdownTimer) {
                        clearInterval(countdownTimer);
                    }

                    // 倒计时逻辑
                    countdownTimer = setInterval(() => {
                        countdown.value--;
                        if (countdown.value <= 0) {
                            clearInterval(countdownTimer);
                            isCodeDisabled.value = false;
                            countdown.value = 60;
                        }
                    }, 1000);

                    alert('验证码已发送，请注意查收');
                    console.log(`向手机号 ${form.value.phone} 发送验证码`);
                } catch (error) {
                    console.error('发送验证码失败:', error);
                    alert('获取验证码失败，请稍后重试');
                    isCodeDisabled.value = false; // 失败时恢复按钮可用
                }
            };
            // 处理注册
            const handleRegister = async () => {

                // 表单验证
                if (!validateForm()) {
                    alert('注册失败，请检查');
                    return;
                }

                isLoading.value = true;

                try {
                    // 第一步：检查手机号是否已注册（查询JSON Server）
                    const checkResponse = await axios.get(
                        `http://localhost:3000/register?phone=${encodeURIComponent(form.value.phone)}`
                    );

                    // 判断是否已存在该手机号
                    if (checkResponse.data && checkResponse.data.length > 0) {
                        alert('手机号已注册，不能重复注册');
                        isLoading.value = false;
                        return;
                    }

                    // 第二步：执行注册（注入JSON Server）
                    const registerResponse = await axios.post('http://localhost:3000/register', {
                        phone: form.value.phone,
                        captcha: form.value.captcha,
                        password: form.value.password,
                        createdAt: new Date().toISOString() // 添加注册时间
                    });

                    // 注册成功处理
                    if (registerResponse.status === 201) { // JSON Server创建成功返回201
                        alert('注册成功，请登录');
                        window.location.href = 'login.html';
                    } else {
                        alert('错误');
                    }
                } catch (error) {
                    console.error('注册过程出错:', error);
                    alert('错误');
                } finally {
                    isLoading.value = false;
                }
            }
            return {
                form,
                errors,
                isLoading,
                captchaCountdown,
                countdown,
                isCodeDisabled,
                getCaptcha,
                validateField,
                handleRegister
            }
        }
    }).mount("#app")
</script>
</body>

</html>